#include <iostream>

using std::cout;
using std::endl;


class Base
{
public:
    Base()
    //: _base(0)
    {   cout << "Base()" << endl;}

    Base(long base)
    : _base(base)
    {   
        cout << "Base(long)" << endl;
    }

    ~Base() {   cout << "~Base()" << endl;  }
    
    virtual void print() const
    {   cout << "Base::_base:" << _base << endl;    }
private:
    long _base;
};

class Derived
: public Base
{
public:
    Derived(long base, long derived)
    : Base(base)//基类构造函数能够调用是因为该构造函数是public的
    , _derived(derived)
    {   cout << "Derived(long,long)" << endl;}

    ~Derived() {    cout << "~Derived()" << endl;}

    void display() const
    {
        cout << "_derived:" << _derived << endl;
    }

private:
    long _derived;
};

int main()
{
    Base base(1);
    base.print();
    cout << endl;

    Derived d1(20, 100);
    d1.display();

    Base * pbase = &base;
    pbase->print();

    //用一个基类指针指向了派生类对象
    pbase = &d1;//向上转型
    pbase->print();


    Derived * pderived = &d1;
    //pderived = &base;//error

    //用一个基类指针赋值给一个派生类指针
    //pderived = (Derived*)pbase;
    pderived = dynamic_cast<Derived*>(pbase);//向下转型, 直接写，语法是要报错的
    if(pderived) {
        cout << "转换成功" << endl;
        pderived->display();
    }
    else {
        cout << "转换失败" << endl;
    }

    Base & ref = base;
    Base & ref2 = d1;
    Derived & ref3 = d1;
    //Derived & ref4 = base;//error

    return 0;
}

